package simonby.top.annualring.adapter.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import simonby.top.annualring.application.service.FamilyTreeApplicationService;
import simonby.top.annualring.application.service.PermissionApplicationService;
import simonby.top.annualring.domain.model.FamilyTree;
import simonby.top.annualring.adapter.dto.FamilyTreeDTO;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 家族树控制器
 * 处理家族树相关的HTTP请求
 */
@RestController
@RequestMapping("/api/family-trees")
public class FamilyTreeController {
    private final FamilyTreeApplicationService familyTreeApplicationService;
    private final PermissionApplicationService permissionApplicationService;

    public FamilyTreeController(FamilyTreeApplicationService familyTreeApplicationService,
                               PermissionApplicationService permissionApplicationService) {
        this.familyTreeApplicationService = familyTreeApplicationService;
        this.permissionApplicationService = permissionApplicationService;
    }

    /**
     * 创建家族树
     * @param familyTreeDTO 家族树DTO
     * @return 创建后的家族树DTO
     */
    @PostMapping
    public FamilyTreeDTO createFamilyTree(@RequestBody FamilyTreeDTO familyTreeDTO) {
        // 设置创建者为当前登录用户
        if (familyTreeDTO.getCreatorId() == null) {
            familyTreeDTO.setCreatorId(StpUtil.getLoginIdAsLong());
        }
        
        FamilyTree familyTree = convertToDomain(familyTreeDTO);
        FamilyTree savedFamilyTree = familyTreeApplicationService.createFamilyTree(familyTree);
        return convertToDTO(savedFamilyTree);
    }

    /**
     * 根据ID获取家族树
     * @param id 家族树ID
     * @return 家族树DTO
     */
    @GetMapping("/{id}")
    public SaResult getFamilyTreeById(@PathVariable Long id) {
        // 检查用户是否有权限访问该家族树
        if (!permissionApplicationService.canAccessFamilyTree(id)) {
            return SaResult.error("无权限访问该家族树");
        }
        
        return familyTreeApplicationService.getFamilyTreeById(id)
                .map(familyTree -> SaResult.data(convertToDTO(familyTree)))
                .orElse(SaResult.error("家族树不存在"));
    }

    /**
     * 根据创建者ID获取家族树
     * @param creatorId 创建者ID
     * @return 家族树DTO列表
     */
    @GetMapping("/creator/{creatorId}")
    public List<FamilyTreeDTO> getFamilyTreesByCreatorId(@PathVariable Long creatorId) {
        // 用户只能查看自己的家族树，管理员可以查看所有
        if (!Objects.equals(StpUtil.getLoginIdAsLong(), creatorId) && !permissionApplicationService.isSystemAdmin()) {
            return null;
        }
        
        return familyTreeApplicationService.getFamilyTreesByCreatorId(creatorId).stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    /**
     * 获取所有家族树
     * @return 家族树DTO列表
     */
    @GetMapping
    public List<FamilyTreeDTO> getAllFamilyTrees() {
        // 只有系统管理员可以获取所有家族树
        if (!permissionApplicationService.isSystemAdmin()) {
            return null;
        }
        
        return familyTreeApplicationService.getAllFamilyTrees().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    /**
     * 更新家族树
     * @param id 家族树ID
     * @param familyTreeDTO 家族树DTO
     * @return 更新后的家族树DTO
     */
    @PutMapping("/{id}")
    public SaResult updateFamilyTree(@PathVariable Long id, @RequestBody FamilyTreeDTO familyTreeDTO) {
        // 检查用户是否有权限编辑该家族树
        if (!permissionApplicationService.canEditFamilyTree(id)) {
            return SaResult.error("无权限编辑该家族树");
        }
        
        familyTreeDTO.setId(id);
        FamilyTree familyTree = convertToDomain(familyTreeDTO);
        FamilyTree updatedFamilyTree = familyTreeApplicationService.updateFamilyTree(familyTree);
        return SaResult.ok("更新成功").setData(convertToDTO(updatedFamilyTree));
    }

    /**
     * 删除家族树
     * @param id 家族树ID
     */
    @DeleteMapping("/{id}")
    public SaResult deleteFamilyTree(@PathVariable Long id) {
        // 检查用户是否有权限删除该家族树
        if (!permissionApplicationService.canManageFamilyTree(id)) {
            return SaResult.error("无权限删除该家族树");
        }
        
        familyTreeApplicationService.deleteFamilyTree(id);
        return SaResult.ok("删除成功");
    }

    /**
     * 将FamilyTreeDTO转换为FamilyTree领域对象
     * @param familyTreeDTO 家族树DTO
     * @return FamilyTree领域对象
     */
    private FamilyTree convertToDomain(FamilyTreeDTO familyTreeDTO) {
        FamilyTree familyTree = new FamilyTree();
        familyTree.setId(familyTreeDTO.getId());
        familyTree.setName(familyTreeDTO.getName());
        familyTree.setDescription(familyTreeDTO.getDescription());
        familyTree.setCreatorId(familyTreeDTO.getCreatorId());
        familyTree.setIsPublic(familyTreeDTO.getIsPublic());
        familyTree.setCreateTime(familyTreeDTO.getCreateTime());
        familyTree.setUpdateTime(familyTreeDTO.getUpdateTime());
        return familyTree;
    }

    /**
     * 将FamilyTree领域对象转换为FamilyTreeDTO
     * @param familyTree FamilyTree领域对象
     * @return 家族树DTO
     */
    private FamilyTreeDTO convertToDTO(FamilyTree familyTree) {
        FamilyTreeDTO familyTreeDTO = new FamilyTreeDTO();
        familyTreeDTO.setId(familyTree.getId());
        familyTreeDTO.setName(familyTree.getName());
        familyTreeDTO.setDescription(familyTree.getDescription());
        familyTreeDTO.setCreatorId(familyTree.getCreatorId());
        familyTreeDTO.setIsPublic(familyTree.getIsPublic());
        familyTreeDTO.setCreateTime(familyTree.getCreateTime());
        familyTreeDTO.setUpdateTime(familyTree.getUpdateTime());
        return familyTreeDTO;
    }
}